var qcloud = require('../../vendor/sdk/index');
var config = require('../../config');
const app = getApp();

Page({
  data: {
    navH: app.globalData.navHeight,
    windowHeight: app.globalData.windowHeight - app.globalData.navHeight,
    windowWidth: app.globalData.windowWidth,
    y: (app.globalData.windowHeight - app.globalData.navHeight) / 2,
    x: app.globalData.windowWidth / 2,
    tabStatus: 1,
    userInfo: null,
    programList: [],
    auditProgramList: [],
    messages: [],
    fileHost: app.globalData.imageUrl,
    programPageSize: 10,
    programPageNum: 1,
    commentPageSize: 10,
    commentPageNum: 1,
    auditPageSize: 10,
    auditPageNum: 1,
    loading: true,
    backgroundAudioManager: null
  },
  onLoad(option) {
    console.log('personalPage.js onLoad', option);
    if (this.data.programList.length > 0 && this.data.messages.length > 0) {
      return;
    }
    this.setData({option});
    app.getUserInfo().then(userInfo => {
      this.setData({
        loading: false,
        userInfo: {
          ...userInfo
        },
      }, () => {
        this.getProgramList();
      });
    });
    this.init();
  },
  init() {
    let self = this;
    if (!this.data.backgroundAudioManager) {
      let backgroundAudioManager = wx.getBackgroundAudioManager();
      // 监听方法
      backgroundAudioManager.onPlay(() => {
        console.log('监听背景音频播放事件');
      });
      backgroundAudioManager.onError(e => {
        console.log('监听背景音频播放错误事件', e);
        console.log('监听到背景音频播放错误事件以后将正在播放的语音条停止闪动');
        let messages = self.data.messages;
        let voiceArr = messages && messages.filter(item => item.msgType === 'voice');
        voiceArr.forEach(msg => {
          if (msg.voicePlay === true) {
            msg.voicePlay = false;
          }
        });
        self.setData({
          messages
        });
      });
      backgroundAudioManager.onPause(() => {
        console.log('监听背景音频暂停事件');
      });
      backgroundAudioManager.onEnded(() => {
        console.log('监听背景音频自然播放结束事件');
        let messages = self.data.messages;
        let voiceArr = messages && messages.filter(item => item.msgType === 'voice');
        voiceArr.forEach(msg => {
          if (msg.voicePlay === true) {
            msg.voicePlay = false;
          }
        });
        self.setData({
          messages
        });
      });
      backgroundAudioManager.onStop(e => {
        console.log('监听背景音频停止事件', e);
      });
      this.backgroundAudioManager = backgroundAudioManager;
      this.setData({
        backgroundAudioManager
      });
    }
  },
  onShow() {
    console.log('personalPage.js onShow');
  },
  onNavBack() {
    // 个人主页返回设置为重定向保证或区域一次最新的互动列表
    let effectiveId = this.data.option && this.data.option.effectiveId;
    wx.redirectTo({
      url: `../index/index?effectiveId=${effectiveId}`
    });
  },
  getUserInfo(e) {
    let self = this;
    // 授权成功
    wx.login({
      success: res => {
        let rawData = e.detail.rawData;
        if (rawData) {
          let userInfo = JSON.parse(rawData);
          let wxUserInfo = {
            code: res.code,
            ...userInfo
          };
          // 设置全局变量并返回上一页
          app.globalData.wxUserInfo = wxUserInfo;
          app.loginIteraction(wxUserInfo, () => {
            // 刷新当前页
            self.onLoad();
          });
        }
      }
    });
  },
  publishProgram() {
    wx.redirectTo({
      url: './publish/publish'
    });
  },
  showModal(e) {
    console.log('auditStatus:', e);
    if (e.currentTarget.dataset.audit && e.currentTarget.dataset.audit === 3) {
      wx.showModal({
        title: '未通过原因',
        content: e.currentTarget.dataset.result,
        showCancel: false,
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定');
          } else if (res.cancel) {
            console.log('用户点击取消');
          }
        }
      });
    }
  },
  onReachBottom() {
    let currentTabStatus = this.data.tabStatus;
    if (currentTabStatus === '1') {
      this.setData({
        programPageNum: this.data.programPageNum + 1
      }, () => {
        this.getProgramList();
      });
    } else if (currentTabStatus === '2') {
      this.setData({
        commentPageNum: this.data.commentPageNum + 1
      }, () => {
        this.getMessages();
      });
    } else if (currentTabStatus === '3') {
      this.setData({
        auditPageNum: this.data.auditPageNum + 1
      }, () => {
        this.getAuditProgramList();
      });
    }
  },
  tabSwitch(e) {
    // 面板切换
    console.log(e.currentTarget.dataset);
    let currentTabStatus = e.currentTarget.dataset.status;
    if (this.data.userInfo && this.data.userInfo.role === -1) {
      this.setData({
        tabStatus: currentTabStatus,
      });
      return;
    }
    this.setData({
      tabStatus: currentTabStatus,
      programList: [],
      auditProgramList: [],
      messages: [],
      programPageSize: 10,
      programPageNum: 1,
      commentPageSize: 10,
      commentPageNum: 1,
      auditPageSize: 10,
      auditPageNum: 1
    }, () => {
      if (currentTabStatus === '1') {
        this.getProgramList();
      } else if (currentTabStatus === '2') {
        this.getMessages();
      } else if (currentTabStatus === '3') {
        this.getAuditProgramList();
      }
    });
  },
  getProgramList() {
    if (this.data.userInfo && this.data.userInfo.role === -1) {
      return;
    }
    // 获取用户发布的分页互动列表
    let self = this;
    qcloud.request({
      url: config.service.getPublishProgramListUrl,
      data: {
        userId: self.data.userInfo.id,
        pageSize: self.data.programPageSize,
        pageNum: self.data.programPageNum
      },
      success: function (res) {
        let programList = res.data.data;
        if (programList && programList.length == 0) {
          return;
        }

        programList && programList.forEach(v => {
          v.startTime = v.startTime.substr(0, 5);
          v.endTime = v.endTime.substr(0, 5);
          v.createDate = v.createDate.substr(0, 19);
          v.auditStatusDesc =
            v.auditStatus === 1
              ? '审核中'
              : v.auditStatus === 2
                ? '通过'
                : v.auditStatus === 3
                  ? '未通过'
                  : '未知状态';
        });

        self.setData({
          programList: self.data.programList.concat(programList)
        });
      }
    });
  },
  getAuditProgramList() {
    // 获取审核列表
    let self = this;
    qcloud.request({
      url: config.service.getAuditProgramListUrl,
      data: {
        auditStatus: 1,
        pageSize: self.data.auditPageSize,
        pageNum: self.data.auditPageNum
      },
      success: function (res) {
        let auditProgramList = res.data.data;
        console.log('auditProgramList', auditProgramList);
        if (auditProgramList && auditProgramList.length == 0) {
          return;
        }

        self.setData({
          auditProgramList: self.data.auditProgramList.concat(auditProgramList)
        });
      }
    });
  },
  getMessages() {
    // 获取评论列表
    let self = this;
    qcloud.request({
      url: config.service.getPagingMessages,
      data: {
        userId: self.data.userInfo.id,
        currentUser: self.data.userInfo.id,
        pageSize: self.data.commentPageSize,
        pageNum: self.data.commentPageNum
      },
      success: function (res) {
        let messages = res.data.data.list;
        console.log('messages', messages);
        if (messages && messages.length == 0) {
          return;
        }
        messages.forEach(message => {
          message.create_time = message.create_time && message.create_time.substr(0, 19);
          message.voicePlay = false;
          if (message.msgType === 'voice' && message.voiceSeconds && message.voiceSeconds !== 'null') {
            let totalWidth = wx.getSystemInfoSync().windowWidth;
            let unit = 2; //
            let startWidth = 46;
            if (totalWidth > 500) {
              unit = 5;
              startWidth = 78;
            }
            message.voiceWidth = startWidth + unit * message.voiceSeconds;
          } else if (message.msgType === 'link') {
            message.content = JSON.parse(message.content);
          }
        });
        self.setData({
          messages: self.data.messages.concat(messages)
        });
      }
    });
  },
  goPersonalInfo() {
    wx.navigateTo({
      url: './personalInfo/personalInfo'
    });
  },
  goAdminManage() {
    wx.navigateTo({
      url: './adminManage/adminManage'
    });
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.target.dataset.src,
      urls: [e.target.dataset.src]
    });
  },
  toRegiste() {
    wx.navigateTo({
      url: './register/register'
    });
  },
  goToComment(e) {
    // 链接到聊天室
    let program = e.currentTarget.dataset.program;
    console.log('program', program);
    if (program && program.auditStatus === 3) {
      wx.showToast({
        title: '未通过审核不能进入聊天室,请重新编辑',
        icon: 'none',
        duration: 2000
      });
      return;
    }
    wx.navigateTo({
      url: '../chat/chat?programId=' + program.id
    });
  },
  editProgram(e) {
    // 编辑互动
    let program = e.currentTarget.dataset.program;
    wx.navigateTo({
      url: './publish/publish?program=' + JSON.stringify(program)
    });
  },
  auditProgram(e) {
    // 审核互动
    let program = e.currentTarget.dataset.program;
    wx.navigateTo({
      url:
        './publish/publish?program=' + JSON.stringify(program) + '&audit=true'
    });
  },
  delProgram(e) {
    // 删除互动
    let self = this;
    wx.showModal({
      content: '确认删除吗？',
      confirmText: '确定',
      cancelText: '取消',
      success: function (res) {
        console.log(res);
        if (res.confirm) {
          let id = e.currentTarget.dataset.programid;
          qcloud.request({
            url: config.service.delProgramUrl,
            data: {
              id: id
            },
            success: () => {
              // 将当前删除的互动从data中去掉
              self.setData({
                programList: self.data.programList.filter(
                  item => item.id !== id
                )
              });
              self.getProgramList(true);
            }
          });
        }
      }
    });
  },
  audioPlay(e) {
    console.log('audioPlay 开始播放语音');
    this.backgroundAudioManager.stop();
    let message = e.currentTarget.dataset.message;
    let messages = this.data.messages;
    messages && messages.filter(item => item.msgType === 'voice').forEach(msg => {
      msg.voicePlay = false;
      if (msg.id === message.id) {
        if (msg.read == 0) {
          msg.firstRead = true;
        }
        msg.voicePlay = true;
        msg.read = 1;
      }
    });
    this.commonAudioPlayFun(message);
    this.setData({
      messages
    });
    // 开启语音播放屏幕常亮
    wx.setKeepScreenOn({
      keepScreenOn: true,
      success: () => {
        console.log('录音播放开启语音播放屏幕常亮');
      }
    });
  },
  audioStop(e) {
    console.log('audioPlay 停止播放语音');
    let message = e.currentTarget.dataset.message;
    let messages = this.data.messages;
    messages && messages.filter(item => item.msgType === 'voice').forEach(msg => {
      if (msg.id === message.id) {
        msg.voicePlay = false;
        msg.firstRead = false;
      }
    });
    // 停止语音播放
    //this.data.innerAudioContext.stop();
    this.backgroundAudioManager.stop();
    this.setData({
      messages
    });
    // 解除语音播放屏幕常亮
    wx.setKeepScreenOn({
      keepScreenOn: false,
      success: () => {
        console.log('手动停止播放录音解除语音播放屏幕常亮');
      }
    });
  },
  commonAudioPlayFun(voiceMessage) {
    if (this.backgroundAudioManager) {
      let self = this;
      let backgroundAudioManager = this.backgroundAudioManager;
      wx.downloadFile({
        url: self.data.fileHost + voiceMessage.content,
        success(res) {
          console.log('下载语音消息 voice-file-res', res);
          if (res.statusCode === 200) {
            console.log('语音消息下载成功,设置背景语音播放地址');
            backgroundAudioManager.title = '互动语音';
            backgroundAudioManager.src = res.tempFilePath;
            self.setData({
              currPlaySrc: res.tempFilePath
            });
          }
        }
      });
    }
  },
  play() {
    wx.navigateTo({
      url: '/pages/play/play'
    })
  }
});
